<?php

namespace App\Http\Controllers\Company;

use App\Exceptions\ApiException;
use App\Http\Requests\BasicRequest;
use App\Libraries\msg\Msg;
use App\Libraries\msg\Push;
use App\Models\ClientUser;
use App\Models\ClientUserHouse;
use App\Models\ClientUserManagerDuty;
use App\Models\ClientUserMessage;
use App\Models\ClientUserRoles;
use App\Models\ClientUserRelationship;
use App\Models\ClientUserRolesHouse;
use App\Models\ClientUserRongcloud;
use App\Models\Config;
use App\Models\House;
use App\Models\HouseDistrict;
use App\Models\HouseDistrictCosts;
use App\Models\ManageMessage;
use App\Models\NeighborCouncilComplaints;
use App\Models\ClientUserWorking;
use Illuminate\Support\Facades\DB;

use App\Models\ClientUserManagerWork;
use App\Models\Message;
class WorkController extends CommonController
{
     private  $uid_in;
     private  $uid_select;
     public function __construct(){
          parent::__construct();

          $uid_in = ClientUserRelationship::treeChildrenOne($this->ship->uid,$this->ship->type);

          $uid_in->prepend(ClientUser::select(['id as uid', 'realname'])->find($this->uid));
          $this->uid_select = $uid_in;
          $this->uid_in= $uid_in->pluck('uid')->toArray();
     }

	public function index()
	{
		$rongcloud_unview_count = ClientUserRongcloud::where(['to_uid' => $this->uid])->unview()->count();
		$costs = $this->costs(new BasicRequest());
		$unpaid_count = collect($costs['data'])->sum('unpaid_count');

		// 待处理投诉
		$complaints = NeighborCouncilComplaints::select(DB::raw('neighbor_council_complaints.id'))
              ->leftJoin('client_user_house as h', 'h.uid', '=', 'neighbor_council_complaints.uid')
              ->where(['parent_id' => 0,  'status' => 1])
              ->whereIn('to_uid',$this->uid_in)
              ->where('h.uid', '>', 0)
              ->groupBy('h.uid')
              ->groupBy('neighbor_council_complaints.id')
              ->pluck('id')
              ->count();

		// 已处理投诉
		$complainted = NeighborCouncilComplaints::select(DB::raw('neighbor_council_complaints.id'))->leftJoin('client_user_house as h', 'h.uid', '=', 'neighbor_council_complaints.uid')->where(['parent_id' => 0, 'status' => 2]) ->whereIn('to_uid',$this->uid_in)->where('h.uid', '>', 0)->groupBy('h.uid')->groupBy('neighbor_council_complaints.id')->pluck('id')->count();
		// 现在是否在工作中
		$working = ClientUser::where(['id' => $this->uid])->value('iswork');
        //内部沟通条数
        $manage_message = ManageMessage::where(['uid'=>$this->uid,'is_view'=>0])->count();
		$return = [
			'working' => $working,
			'rongcloud_unview_count' => group99($rongcloud_unview_count),
			'unview_message_count' => group99(ClientUserMessage::where(['uid' => $this->uid, 'viewed' => 0])->count()),
			'unpaid_count' => $unpaid_count,
			'complaints' => $complaints,
			'complainted' => $complainted,
            'manage_message' =>$manage_message?$manage_message:0,
		];
		return json_success('OK', $return);
	}
	
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 开始值班
	 */
	public function switch(BasicRequest $request)
	{
          /* 值班改为不判断
           * $UserWorking = ClientUserWorking::select('id')->where(['uid'=>$this->uid,'status'=>1])->first();*/
          ClientUserManagerDuty::switch ($this->uid);

          $iswork=ClientUser::select('iswork')->where(['id'=>$this->uid])->first();
          if($iswork->iswork==1){
               ClientUser::where(['id'=>$this->uid])->update(['iswork'=>0]);
               return json_return([], '', '已结束服务');
          }else{
               ClientUser::where(['id'=>$this->uid])->update(['iswork'=>1]);
               return json_return([], '', '开始服务');
          }
	}
     //筛选管理员
	public function service_list(BasicRequest $request)
     {
          $uid_list=ClientUserRelationship::getTree($this->ship,$this->user);
         if(is_array($uid_list)) {
               if(count($uid_list)==0){
                    $uid_list=array();
               }
          }else{
              if(!$uid_list->first()) {
                   $uid_list = array();
              }
          }


          return json_success('OK',$uid_list);
     }
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 管理人员融云聊天记录与未读列表
	 */
	public function rongcloud(BasicRequest $request)
	{
        set_time_limit(0);
		$house_id = $request->input('house_id', 0);
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
		$uid = $request->input('uid');
        $uid_in = $this->uid_in;

		if($uid) {
           $type = ClientUserRoles::where(['uid' => $uid])->value('type');
           if($type!=5){
                $uid_in=  ClientUserRelationship::treeChildrenOne($uid,$type);
                $uid=null;
           }
        }

		$uid_select = $this->uid_select;
		$uid_select->prepend(['uid' => 0, 'realname' => '全部']);

		$data = ClientUserRongcloud::select(DB::raw('client_user_rongcloud.id,house.house_sn as house_long,from_uid,to_uid,u.avatar,house.house_sn as username,mobile,client_user_rongcloud.created_at,client_user_rongcloud.type,content,h.house_id'))
              ->leftJoin('client_user as u', 'u.id', '=', 'client_user_rongcloud.from_uid')
              ->leftJoin('client_user_house as h', 'h.uid', '=', 'client_user_rongcloud.from_uid')
              ->leftJoin('house', 'house.house_id', '=', 'h.house_id')
			->where(function ($query) use ($uid_in) {
				$in = ClientUserRongcloud::select(DB::raw('max(id) id'))->whereIn('to_uid', $uid_in)->groupBy('from_uid')->groupBy('to_uid')->pluck('id');
				$query->whereIn('client_user_rongcloud.id', $in);
			})
			->when($house_id, function ($query) use ($house_id) {
				$house_id_child = HouseDistrict::treeChildrenOne($house_id, 'id')->pluck('id');
				// 把自己加入筛选中
				$house_id_child->prepend($house_id);
				$query->whereIn('house.house_id', $house_id_child);
			})
			->when($uid, function ($query) use ($uid) {
				$query->where(['client_user_rongcloud.to_uid' => $uid]);
			})
			->when($start_time, function ($query) use ($start_time) {
				$start_time = time2date(strtotime($start_time));
				$query->where('client_user_rongcloud.created_at', '>=', $start_time);
			})
			->when($end_time, function ($query) use ($end_time) {
				$end_time = time2date(strtotime($end_time . ' 23:59:59'));
				$query->where('client_user_rongcloud.created_at', '<=', $end_time);
			})
			->orderBy('client_user_rongcloud.id', 'desc')
			->pages()
			->each(function ($v, $k) {
				$v->unview_count = ClientUserRongcloud::where(['from_uid' => $v->from_uid, 'to_uid' => $this->uid])->unview()->count();
				if ($v->type == 'RC:TxtMsg') {
					$v->content = str_limit(json_decode($v->content)->content, 10);
				} else {
					$v->content = '[不支持预览]';
				}
			});
//		$house = HouseDistrict::treeChildren(0, 'id,name');
        $house = HouseDistrict::select('id','name','type')->whereIn('id',explode(',',$this->ship->house_id))->get();
		$return = [
            'house'   =>$house,
			'manager' => $uid_select,
			'list' => $data,
		];
		return json_success('OK', $return);
	}
	
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 房屋管家聊天设置为已读，app每次进来都要请求接口
	 */
	public function rongcloud_viewed(BasicRequest $request)
	{
		$from_uid = $request->input('from_uid');
		$var = ClientUserRongcloud::where(['from_uid' => $from_uid, 'to_uid' => $this->uid])->update(['viewed' => 1]);
		return json_success('消息阅读完成');
	}
	
	/**
	 * @param BasicRequest $request
	 * @throws ApiException
	 * @return array
	 * 管家结束聊天服务，业主端需要跳出评价框
	 */
	public function rongcloud_complete(BasicRequest $request)
	{
		$from_uid = $request->input('from_uid');
          $insert=array(
              'from_uid'=>$from_uid,
              'to_uid'=>$this->uid,
              'end_time'=>date('Y-m-d H:i:s')
          );
		DB::table('client_user_rongcloud_end')->insert($insert);
		if (empty($from_uid)) {
			throw new ApiException('来源用户参数必传');
		}
		$push = new Push();
		$push->queue($from_uid, '服务已结束', '管家服务已完成，快点击进行服务评价吧~~', ['type' => 'rongcloud_complete', 'from_uid' => $this->uid]);
		return json_success('服务结束');
	}
	
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 缴费管理，统计
	 */
	public function costs(BasicRequest $request)
	{
        $house_id = $this->ship->house_id;
        $house=HouseDistrict::select('name')->where(['id'=>$house_id])->first();
		// 查询出我管理的房屋列表，管家按栋分布，直接查找二级房屋即可
        $unpay_count = HouseDistrictCosts::where(['pay_status' => 0])
            ->leftJoin('client_user_roles_house','house_district_costs.house_id','=','client_user_roles_house.house_id')
            ->whereIn('uid',$this->uid_in)->groupBy('house_district_costs.house_id')
            ->get()->count();

        $pay_count = HouseDistrictCosts::where(['pay_status' => 1])
            ->leftJoin('client_user_roles_house','house_district_costs.house_id','=','client_user_roles_house.house_id')
            ->whereIn('uid',$this->uid_in)->groupBy('house_district_costs.house_id')->get()->count();

        $data=[array(
            'house_id'=>$house_id,
            'name_long'=>$house->name,
            'paid_count'=>$pay_count,
            'unpaid_count'=>$unpay_count,
        )];
		
		return json_success('OK', $data);
	}
    /**
     * @param BasicRequest $request
     * @return array
     * 缴费列表新版
     */
	public function costs_list(BasicRequest $request){
        $house_id = $request->input('house_id', 0);
        $pay_status = $request->input('pay_status');
        $keyword = $request->input('keyword');
        $h_ids = explode(',',$this->ship->house_id);
        $house = HouseDistrict::select('id','name','type')->whereIn('id',$h_ids)->get();

        $paid_select = [
            ['pay_status' => '0,1', 'name' => '全部'],
            ['pay_status' => '1', 'name' => '已缴费'],
            ['pay_status' => '0', 'name' => '未缴费'],
        ];

        $data = House::leftJoin('house_district_owner','house.house_id','=','house_district_owner.house_id')
            ->leftJoin('client_user_roles_house as roles_house','house.house_id','=','roles_house.house_id')
            ->leftJoin('house_district_costs','house_district_costs.house_id','=','house.house_id')
            ->groupBy('house.house_id')
            ->select('house.house_id','house.house_sn','house_district_owner.mobile','house_district_owner.realname',DB::raw('min(house_district_costs.pay_status) as pay_status'))
            ->when($keyword,function($query) use($keyword){
                $query->where('house_district_owner.realname','like','%'.$keyword.'%')
                    ->orWhere('house.house_sn','like','%'.$keyword.'%')
                    ->orWhere('house_district_owner.mobile','like','%'.$keyword.'%');;
            })
            ->when($pay_status,function($query) use($pay_status){
                $query->whereIn('pay_status',explode(',',$pay_status));
            })
            ->where(function($query){
                if($this->ship->type==5){
                    //分区经理
                    $query->where('house.partition_id','=',$this->ship->house_id);
                }else if($this->ship->type==4){
                    //管家
                    $query ->where('roles_house.uid','=',$this->uid);
                }else if($this->ship->type==3){
                    //主管
                    $uid_in = ClientUserRelationship::treeChildrenOne($this->ship->uid,3)->pluck('uid');
                    $query ->whereIn('roles_house.uid',$uid_in)->groupBy('roles_house.house_id');
                }else if($this->ship->type==2){
                    //项目经理
                    $query->where('house.village_id','=',$this->ship->house_id);
                }else if($this->ship->type=1){
                    $h_ids=explode(',',$this->ship->house_id);
                    $query->whereIn('house.village_id',$h_ids);
                }
            })->when($house_id,function($query) use ($house_id){
                //根据house_id获取类别查询
                if($house_id>0) {
                    $house_type = HouseDistrict::where('id', '=', $house_id)->value('type');
                    switch ($house_type) {
                        case 2:
                            $query->where('house.village_id','=',$house_id);
                            break;
                        case 3:
                            $query->where('house.budding_id','=',$house_id);
                            break;
                        case 4:
                            $query->where('house.unit_id','=',$house_id);
                            break;
                        case 5:
                            $query->where('house.floor_id','=',$house_id);
                            break;
                        case 6:
                            $query->where('house.house_id','=',$house_id);
                            break;
                        case 7:
                            $query->where('house.partition_id','=',$house_id);
                            break;
                    }
                }
            })->orderBy('house_sn','desc')->pages()->each(function($v,$k){
                $is_register = ClientUserHouse::where(['house_id'=>$v->id])->first();
                $v->is_resgiter = $is_register ? 1 : 0;
                $v->uid = $is_register->uid;
                $v->amount = HouseDistrictCosts::where(['house_id'=>$v->house_id,'pay_status'=>0])->sum('amount');
            });
        $return = [
            'house'		=> $house,
            'paid_select' => $paid_select,
            'list'	=> $data
        ];
        return json_success('OK',$return);
    }

	/**
	 * @param BasicRequest $request
	 * @return array
	 * 缴费列表，筛选
	 */
	public function costs_filter(BasicRequest $request)
	{
		$house_id = $request->input('house_id', 0);
		$pay_status = $request->input('pay_status', '0,1');
		
		$paid_select = [
			['pay_status' => '0,1', 'name' => '全部'],
			['pay_status' => '1', 'name' => '已缴费'],
			['pay_status' => '0', 'name' => '未缴费'],
		];

		// 可到可筛选的楼层信息
		$house_ids = collect([]);
		$house_children = collect([]);
		$house_id_unpaid = collect([]);        // 待缴房屋费用列表
		$house_id_paid = collect([]);        // 已缴房屋费用列表
		$house_id_costs = collect([]);        // 全部房屋费用列表

		HouseDistrict::select(['id', 'name'])->where(['parent_id' => $this->ship->house_id])->get()->each(function ($v, $k) use (&$house_children) {
//			$v->children = HouseDistrict::treeChildren($v->id, 'id,name');
			$type2 = HouseDistrict::select(['id', 'name'])->where(['parent_id' => $v->id])->get();
			$house_children = $house_children->merge($type2);
		});
		// 可筛选的管辖房屋
		$house = $house_children->each(function($v,$k){
			$v->children = HouseDistrict::treeChildren($v->id, 'id,name');
		});

		if($house_id){
			$house_children = HouseDistrict::select(['id', 'name'])->where(['id'=>$house_id])->get();
		}
		$house_children->each(function ($v, $k) use (&$house_ids, &$house_id_unpaid, &$house_id_paid, &$house_id_costs) {
			$house_id_child = HouseDistrict::treeChildrenOne($v->id, 'id')->pluck('id');
			$house_id_child->push($v->id);
			$house_ids = $house_ids->merge($house_id_child);
			
			// 查找此二级房屋下面的待缴费数据
			$house_id_unpaid2 = HouseDistrictCosts::where(['pay_status' => 0])->whereIn('house_id', $house_id_child)->groupBy('house_id')->pluck('house_id');
			// 查找此二级房屋下面的缴费数据
			$house_id_costs2 = HouseDistrictCosts::whereIn('house_id', $house_id_child)->groupBy('house_id')->pluck('house_id');
			$house_id_paid2 = $house_id_costs2->diff($house_id_unpaid2);

			$house_id_unpaid = $house_id_unpaid->merge($house_id_unpaid2);
			$house_id_paid = $house_id_paid->merge($house_id_paid2);
			$house_id_costs = $house_id_costs->merge($house_id_costs2);
		});

		$query = HouseDistrictCosts::select(DB::raw('u.id as uid, house_district_costs.house_id,u.username,u.realname,u.mobile,u.avatar, min(pay_status) pay_status'))
			->leftJoin('client_user_house as h',function($query){
				$query->on('h.house_id', '=', 'house_district_costs.house_id');
			})
			->leftJoin('client_user as u', 'u.id', '=', 'h.uid')
//			->where(['u.type'=>1])
			->groupBy('house_district_costs.house_id')
			->orderBy('house_district_costs.id','desc');

		switch ($pay_status) {
			case '0' :
				$query->whereIn('house_district_costs.house_id', $house_id_unpaid);
				break;
			case '1' :
				$query->whereIn('house_district_costs.house_id', $house_id_paid);
				break;
			default :
				$query->whereIn('house_district_costs.house_id', $house_id_costs);
				break;
		}
		
		$list = $query->pages()->each(function($v,$k){
			$v->amount = HouseDistrictCosts::where(['house_id'=>$v->house_id,'pay_status'=>0])->sum('amount');
			$v->house_long = House::where('house_id','=',$v->house_id)->first()->house_sn;
			$v->avatar  = $v->avatar ?? config('basic.avatar');
			$v->username = $v->realname  = $v->realname ?? '[未注册]';

			$v->uid = $v->uid ?? 0;
		});
		
		$return = [
			'house' => $house,
			'pay_status' => $paid_select,
			'list' => $list
		];
		
		return json_success('OK', $return);
	}
	
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 某一房屋的待缴费列表
	 */
	public function costs_unpaid(BasicRequest $request)
	{
		$house_id = $request->input('house_id');
		$data = HouseDistrictCosts::where(['house_id' => $house_id])->unpaid()->pages();
		return json_success('OK', $data);
	}
	
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 某一房屋的已缴费列表
	 */
	public function costs_paid(BasicRequest $request)
	{
		$house_id = $request->input('house_id');
		$data = HouseDistrictCosts::where(['house_id' => $house_id])->paid()->pages();
		return json_success('OK', $data);
	}
	
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 发送催缴短信
	 */
	public function costs_message(BasicRequest $request)
	{
		$house_id = $request->input('house_id');
		$uid = ClientUserHouse::where(['house_id' => $house_id])->value('uid');
		$mobile = ClientUser::where(['id' => $uid])->value('mobile');
		// 发送短信
		$msg = new Msg();
		$msg->queue($mobile, '催缴费用', ['param' => 'value']);
		return json_success('短信发送成功');
	}
	
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 我收到的投诉列表
	 */
	public function complaints(BasicRequest $request)
	{

		$house_id = $request->input('house_id');
		$status = $request->input('status');
		$house = HouseDistrict::select(['id as house_id', 'name as name_long'])->where('parent_id','=',$this->ship->house_id)->get();
		$house->prepend(['house_id' => 0, 'name_long' => '全部']);
          DB::enableQueryLog();
		$list = NeighborCouncilComplaints::select(DB::raw('neighbor_council_complaints.id,h.uid,house_id,u.username,u.realname,u.mobile,u.avatar'))
              ->leftJoin('client_user as u', 'u.id', '=', 'neighbor_council_complaints.uid')
              ->leftJoin('client_user_house as h', 'h.uid', '=', 'u.id')
              ->orderBy('neighbor_council_complaints.id', 'desc')->where(['neighbor_council_complaints.parent_id' => 0])
              ->whereIn('neighbor_council_complaints.to_uid',$this->uid_in)
			->where('h.uid', '>', 0)
			->when($house_id, function ($query) use ($house_id) {
				$house_id_in = HouseDistrict::treeChildrenOne($house_id, 'id')->pluck('id');
				$query->whereIn('h.house_id', $house_id_in);
			})
			->when($status, function ($query) use ($status) {
				$query->where(['neighbor_council_complaints.status' => $status]);
			})
			->groupBy('h.uid')
               ->groupBy('neighbor_council_complaints.id')
			->pages()->each(function ($v, $k) {
				$v->house_long = HouseDistrict::findOrFail($v->house_id)->sn;
				$last = NeighborCouncilComplaints::findOrFail($v->id)->detail()->history->last();
				$v->last_description = $last->description;
				$v->created_at = $last->created_at;
			});
		// 设置站内信为已读
		ClientUserMessage::where(['uid' => $this->uid, 'type_id' => 7])->update(['viewed' => 1]);
		$return = [
			'house' => $house,
			'list' => $list,
		];
		return json_success('OK', $return);
	}
	
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 投诉详情
	 */
	public function complaints_detail(BasicRequest $request)
	{
		$id = $request->input('id');
		$data = NeighborCouncilComplaints::findOrFail($id)->detail();

		$house_id = ClientUserHouse::where(['uid' => $data->uid])->value('house_id');
		$data->name_long = House::where('house_id','=',$house_id)->value('house_sn');
		return json_success('OK', $data);
	}
	
	/**
	 * @param BasicRequest $request
	 * @throws ApiException
	 * @return array
	 * 投诉回复
	 */
	public function complaints_reply(BasicRequest $request)
	{
		$id = $request->input('id');
		$description = $request->input('description', '您好，请详细描述您的问题');
		$data = NeighborCouncilComplaints::findOrFail($id)->detail();
		if ($data->status != 1) {
			throw new ApiException('该问题已经标记为完成，无法继续回复');
		}
		$last = $data->history->pop();
		$add = [
			'uid' => $last->uid,
			'admin_uid' => $this->uid,
			'to_uid' => $this->uid,
			'parent_id' => $last->id,
			'description' => $description,
			'status' => 1,
		];
		$id = NeighborCouncilComplaints::create($add)->id;
		$push = new Push();
		$push->queue($last->uid, '收到新的投诉信息反馈', $description, ['type' => 'complaints_reply', 'complaints_id' => $id, 'messages_type_id' => 2]);
		return json_return($id, '', '回复成功');
	}
	
	/**
	 * @param BasicRequest $request
	 * @throws ApiException
	 * @return array
	 * 投诉点击完成
	 */
	public function complaints_complete(BasicRequest $request)
	{
		$id = $request->input('id');
		$data = NeighborCouncilComplaints::findOrFail($id)->detail();
		if ($data->status != 1) {
			throw new ApiException('该问题已经标记为完成，无法继续回复');
		}
		$last = $data->history->pop();
		$last_id = $last->id;
		$var = NeighborCouncilComplaints::where(['id' => $last_id])->update(['status' => 2, 'remarks' => '系统结束服务']);
		
		$push = new Push();
		$push->queue($last->uid, '收到新的投诉处理结果', '点击进行评价吧~', ['type' => 'company_complaints_complete', 'complaints_id' => $id, 'messages_type_id' => 2]);
		return json_return($var, '', '处理成功');
	}


	/**
	 * @param BasicRequest $request
	 * @return array
	 * 值班管家（已迁移）
	 */
	public function duty(BasicRequest $request)
	{
		$user = $this->user;
		$check = ClientUserWorking::where(['uid'=>$this->uid,'status'=>1])->first();
		$h = $this->_getworkarea();
		if($check){
			$house_id = is_numeric($h->village_id) ? [$h->village_id] : explode(',', $h->village_id);
			$working = 1;
		}else{
			$house_id = is_numeric($h->house_id) ? [$h->house_id] : explode(',', $h->house_id);
			$working = 0;
		}
		$house = HouseDistrict::select('id as house_id','type','name as name_long')->whereIn('id',$house_id)->first();
		$return =[];
		switch ($house->type) {
			case 7:
				$house2 = HouseDistrict::select('id as house_id','type','parent_id','name as name_long')->where(['parent_id' => $house->house_id])->get();
				foreach ($house2 as $v) {
					$return[] = ['house_id'=>$v->house_id,'name_long'=>$v->name_long];
				}
				break;
			case 3:
				$return[] = ['house_id'=>$house->house_id,'name_long'=>$house->name_long];
				break;
			case 2:
				$house2 = HouseDistrict::select('id as house_id','type','parent_id','name as name_long')->where(['parent_id' => $house->house_id])->get();
				foreach ($house2 as $v) {
					$house3 = HouseDistrict::select('id as house_id','type','parent_id','name as name_long')->where(['parent_id' => $v->house_id])->get();
					$d = [];
					foreach ($house3 as $vv) {
						$d[] = array(
								'house_id'=>$vv->house_id,
								'name_long'=>$house->name_long.$v->name_long.$vv->name_long,
							);
					}
					$return = array_merge($return,$d);
				}
				break;
		}
		$user->house = $return;
		$re = [
			'working' => $working,
			'user' => $user
		];
		return json_success('OK', $re);
	}
	
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 值班服务数据
	 */
	public function duty_filter(BasicRequest $request)
	{
		$uid = $request->input('uid');    // 筛选管家
		$house_id = $request->input('house_id');
		$start_time = $request->input('start_time');
		$end_time = $request->input('end_time');
		$filter = $request->input('filter');
        $uid_in = ClientUserRelationship::treeChildrenOne($this->ship->uid,$this->ship->type);
        $uid_select = $uid_in->prepend(ClientUser::select(['id as uid', 'realname'])->find($this->uid));
        $uid_select->prepend(['uid' => 0, 'realname' => '全部']);
        if($uid) {
           $type = ClientUserRoles::where(['uid' => $uid])->value('type');
           if($type!=4){
                $uid_in = ClientUserRelationship::treeChildrenOne($uid,$type);
                $uid = null;
           }else{
                $uid_in = $uid_in->pluck('uid');
           }
        }else{
           $uid_in = $uid_in->pluck('uid');
        }
		
		// 筛选类型，week/month
		$time_type = $request->input('time_type');
		// 之前时间个数，根据 time_type 不同而不同
		$time_before_count = $request->input('time_before_count', 0);
		$type_start_time = '';
		$type_end_time = time2date();
		if ($time_type == 'week') {
               $start_time = time2date(strtotime(date('Y-m-01 00:00:00')) + $time_before_count * 7 * 86400);
               $time_before_count_end = $time_before_count + 1;
               $end_time = time2date(strtotime(date('Y-m-01 00:00:00')) + $time_before_count_end * 7 * 86400);
		} elseif ($time_type == 'month') {
			$type_start_time = date('Y-m-01 00:00:00', strtotime("-$time_before_count months"));
			$type_end_time = date('Y-m-d 23:59:59', strtotime("$type_start_time +1 months -1 days"));
		}

        $data = ClientUserManagerDuty::select(DB::raw('client_user_manager_duty.id,client_user_manager_duty.uid,client_user_manager_duty.date,u.username,u.avatar,u.realname,u.mobile,start_time,end_time,client_user_manager_duty.created_at'))
        ->leftJoin('client_user as u', 'u.id', '=', 'client_user_manager_duty.uid')
        ->whereIn('client_user_manager_duty.uid', $uid_in)
        ->when($type_start_time, function ($query) use ($type_start_time, $type_end_time) {
            $query->where('client_user_manager_duty.created_at', '>', $type_start_time)->where('client_user_manager_duty.created_at', '<=', $type_end_time);
        })
        ->when($filter,function($query) use($filter){
            if($filter==1){
                $query->leftJoin('client_user_manager_works as work','work.uid','=','client_user_manager_duty.uid')->where('work.type','=',1)->whereRaw('work.date = client_user_manager_duty.date');
            }
        })
        ->when($house_id, function ($query) use ($house_id) {
            $manager_uids = HouseDistrict::treeChildrenOne($house_id, 'manager_uid')->pluck('manager_uid');
            $query->whereIn('uid', $manager_uids);
        })
        ->when($uid, function ($query) use ($uid) {
            $query->where('uid', '=', $uid);
        })
        ->when($start_time, function ($query) use ($start_time) {
            $start_time = strtotime($start_time);
            $query->where('start_time', '>=', $start_time);
        })
        ->when($end_time, function ($query) use ($end_time) {
            $end_time = strtotime($end_time . ' 23:59:59');
            $query->where('end_time', '<=', $end_time);
        })
        ->groupBy('date')
        ->orderBy('client_user_manager_duty.id', 'desc')
        ->pages()->each(function ($v, $k) {
            // 计算当天值班时间
            $v->duty_hour = round(((($v->end_time>0)?$v->end_time:time()) - $v->start_time) / 3600, 2);
            // 当天与其他人聊天人数
            $v->chat_count = ClientUserRongcloud::where(['to_uid' => $v->uid])->whereRaw('date_format(created_at,\'%Y-%m-%d\') = \'' . $v->date . '\'')->groupBy(DB::raw('from_uid,date_format(created_at, \'%Y-%m-%d\')'))->pluck('id')->count();
            // 当天处理投诉次数
            $v->complaints = NeighborCouncilComplaints::where(['parent_id' => 0, 'to_uid' => $v->uid, 'status' => 2])->whereRaw('date_format(created_at,\'%Y-%m-%d\') = \'' . $v->date . '\'')->count();
            $have_log = ClientUserManagerWork::where(['uid'=>$v->uid])->where('date','=',$v->date)->where('type','=',1)->count();
            $v->have_log = $have_log>0?1:0;
        });
        $house = HouseDistrict::select(['id as house_id','name as name_long'])
          ->whereIn('id',explode(',',$this->ship->house_id))
          ->get()->each(function($v,$k){
               $v->children = HouseDistrict::select(['id as house_id','name as name_long'])->whereIn('id',explode(',',$v->house_id))->get();
               $v->children->prepend(['house_id'=>$v->house_id,'name_long'=>'全部']);
          });
        $house->prepend(['house_id'=>0,'name_long'=>'全部']);
		$time_week_pad = $time_month_pad = [];
          for ($i = 0; $i <5; $i++) {
               $time_week_pad[] = ['name' => date( 'Y年m月第'.($i+1) .'周'), 'value' => $i];
          }
		  for ($i=0;$i<40;$i++){
			   $time_month_pad[] = ['name' => date('Y年m月', strtotime("-$i months")), 'value' => $i];
		  }
		$time = [
			['name' => '全部', 'value' => '', 'children' => []],
			['name' => '按周查看', 'value' => 'week', 'children' => $time_week_pad],
			['name' => '按月查看', 'value' => 'month', 'children' => $time_month_pad],
		];
		$return = [
			'manager' => $uid_select,
			'house' => $house,
			'time' => $time,
			'list' => $data,
		];
		return json_success('OK', $return);
	}
	
	/**
	 * @param BasicRequest $request
	 * @throws ApiException
	 * @return array
	 * 查看值班时间工作日志
	 */
	public function duty_work(BasicRequest $request)
	{
		$id = $request->input('id');    //值班id

		$duty = ClientUserManagerDuty::find($id);
		$start_time = date('Y-m-d H:i:s', $duty->start_time);
		$end_time = date('Y-m-d H:i:s', $duty->end_time);
		
		$data = ClientUserManagerWork::select(['client_user_manager_works.*','u.username','u.realname','u.mobile'])
			->where(['client_user_manager_works.uid' => $duty->uid])
			->where('client_user_manager_works.created_at', '>=', $start_time)
			->where('client_user_manager_works.created_at', '<=', $end_time)
			->leftJoin('client_user as u', 'u.id', '=', 'client_user_manager_works.uid')
			->pages()
			->each(function ($v) {
				$images = $v->images()->pluck('image');
				$v->image = $images->first();
				$v->images = $images;
			});
		
		$return = [
			//'duty' => $duty,
			'list' => $data,
		];
		
		return json_success('OK', $return);
	}
	/**
	 * @param BasicRequest $request
	 * @throws ApiException
	 * @return array
	 * 更新值班状态
	 */
	public function isworking(BasicRequest $request){
		$check = $request->input('status');
		$status = 1; //值班中的状态
		if($check==1){ //检测是否在值班
			$UserWorking = ClientUserWorking::select('id')->where(['uid'=>$this->uid,'status'=>1])->first();
			return json_success('ok',['isworking'=>$UserWorking->id ? 1 : 0]); //1值班 0未值班
		}
		$h = $this->_getworkarea();
		$house_id = is_numeric($h->house_id) ? [$h->house_id] : explode(',', $h->house_id);
		$house = HouseDistrict::select('id','type','parent_id')->whereIn('id',$house_id)->first();
		switch ($house->type) {
			case 7:
				break;
			case 3:
				$house = HouseDistrict::select('id','type','parent_id')->where(['id' => $house->parent_id])->first();break;
			case 2:
				$house = HouseDistrict::select('id','type','parent_id')->where(['parent_id' => $house->id])->first();break;
		}
		$house_id = $house->type==7 ? $house->id : '';
		if($house_id==='') return json_error('fail','您不符合值班条件');
		$working = ClientUserWorking::select('uid','house_id','status','updated_at','created_at')->where(['house_id'=>$house_id])->get();
		// insert 判断是插入还是更新 1为更新 uid 为当前值班的人的id
		$insert = $uid = 0;
		$_status = $status == 1 ? 0 : 1;
		$time = time();
		$date = date('Y-m-d H:i:s');
		foreach ($working as $k => $v) {
			// 小区正在值班的人
			if($v->status==1){
				$uid = $v->uid;
			}
			// 数据库有这个人的信息 从非值班改为值班状态
			if($v->uid==$this->uid){
				if($v->status==1) return json_error('fail','您已经处于值班中！');
				$insert  = 1; // 不添加新记录
			}
		}
		// 把小区正在值班的其他人状态改为结束值班 值班日志也要写入结束时间
		if($uid){
			ClientUserManagerDuty::where(['uid'=>$uid,'date'=>date('Y-m-d'),'status'=>1])->update(['end_time'=>$time,'updated_at'=>$date,'status'=>0]);
			ClientUserWorking::where(['house_id'=>$house_id,'uid'=>$uid,'status'=>$status])->update(['status' => $_status,'updated_at'=>$date]);
		}
		// 数据库没有这个人的值班信息 插入一条新值班纪录
		if($insert===0){
			ClientUserWorking::create(['created_at'=>$date,'status'=>1,'house_id'=>$house_id,'uid'=>$this->uid,'date'=>date('Y-m-d')]);
		}else if($insert===1){
			ClientUserWorking::where(['house_id'=>$house_id,'uid'=>$this->uid,'status'=>$_status])->update(['status' => $status,'updated_at'=>$date]);
		}
		// 插入值班记录 和值班开始时间
		$data = [];
		$data['uid'] = $this->uid;
		$data['start_time'] = $time;
		$data['status'] = 1;
		$data['created_at'] = $date;
		$data['updated_at'] = $date;
		$data['date'] = date('Y-m-d');
	    ClientUserManagerDuty::insert($data);
		return json_success('ok',['isworking'=>$status]);
	}
	private function _getworkarea(){
		return ClientUser::select(DB::raw('client_user_relationship.house_id,client_user_relationship.village_id')) 
			->leftJoin('client_user_roles','client_user.id','=','client_user_roles.uid')
			->leftJoin('client_user_relationship','client_user_roles.ship_id','=','client_user_relationship.id')
			->where('client_user.id','=',$this->uid)
			->first();
	}
}